package com.zhuang.taiqiu.netty.handler;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.zhuang.taiqiu.config.GCmd;
import com.zhuang.taiqiu.config.SessionManage;
import com.zhuang.taiqiu.config.UserState;
import com.zhuang.taiqiu.model.Player;
import com.zhuang.taiqiu.model.RoomInfo;
import com.zhuang.taiqiu.model.User;
import com.zhuang.taiqiu.model.vo.PlayerVO;
import com.zhuang.taiqiu.model.vo.RoomInfoVO;
import com.zhuang.taiqiu.proto.GameMessageOuterClass;
import com.zhuang.taiqiu.proto.GameMessageOuterClass.GameMessage;
import com.zhuang.taiqiu.utils.NettyUtil;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.util.concurrent.GlobalEventExecutor;
import org.apache.commons.lang3.RandomUtils;
import org.springframework.stereotype.Component;

import java.time.Instant;
import java.util.Random;

@Component
public class RoomHandler {


    public void mataRoom(ChannelHandlerContext ctx, GameMessage msg){
        /**
         * 从队列中，随机抽出一个玩家
         * 添加到通道组里，作为房间，返回房间id
         * 获取出来是否相同，相同的不让匹配成果
         */
        JSONObject jsonParse = JSON.parseObject(msg.getData());
        Long userId = jsonParse.getLong("userId");

        RoomInfoVO roomInfoVO = new RoomInfoVO();
        Long playerId = SessionManage.getMatch(userId);
        if(null == playerId || playerId == userId){
            Player myPlayer = SessionManage.getChannel(userId);
            myPlayer.getUser().setState(UserState.MATCH_STATE);/**修改为匹配状态*/
            if(playerId != userId){
                SessionManage.putMatch(userId);
            }
            roomInfoVO.setRoomId(-1L);
            NettyUtil.sendMsg(ctx.channel(), roomInfoVO, GCmd.S2C.MATCH_PLAYER_SYNC.getDescription());
            /**等待玩家*/
        }else{
            Player player = SessionManage.getChannel(playerId);
            Player myPlayer = SessionManage.getChannel(userId);
            /**匹配成功，同时要通知那个匹配成功的玩家*/
            Channel channel = player.getChannel();

            /**把两个玩家都放入房间后，再群发*/
            ChannelGroup channelGroup = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);
            channelGroup.add(ctx.channel());/**当前玩家通道*/
            channelGroup.add(channel);/**被匹配玩家通道*/

            /**封装到内存保存一份**/
            RoomInfo roomInfo = new RoomInfo();
            long roomId = Instant.now().toEpochMilli();/**暂时用当前时间戳做为房间ID*/
            roomInfo.setRoomId(roomId);
            roomInfo.setChannelGroup(channelGroup);
            roomInfo.setPlayerA(myPlayer);
            roomInfo.setPlayerB(player);

            Random rand = new Random();
            int resultNum = rand.nextInt(2) + 1;
            Long currentPlayer = resultNum == 1 ? myPlayer.getUser().getId() : player.getUser().getId();
            roomInfo.setCurrentPlayer(currentPlayer);/**默认玩家A就是发球人【这里可以改成随机玩家A或B是发起人。而不是由前端来选】*/
            SessionManage.bindChannelGroup(roomId, roomInfo);

            /**封装成房间实体，发送给匹配中的玩家*/

            myPlayer.getUser().setState(UserState.PVP_STATE);/**修改为对战状态*/
            player.getUser().setState(UserState.PVP_STATE);/**修改为对战状态*/
            roomInfoVO.setRoomId(roomId);
            roomInfoVO.setPlayerA(myPlayer.getUser());
            roomInfoVO.setPlayerB(player.getUser());
            roomInfoVO.setCurrentPlayer(currentPlayer);

            NettyUtil.sendGroupMsg(channelGroup, roomInfoVO, GCmd.S2C.MATCH_PLAYER_SYNC.getDescription());
        }

    }

    public void cancelMataRoom(ChannelHandlerContext ctx, GameMessage msg) {
        /**
         * 从队列里删除
         */
        JSONObject jsonParse = JSON.parseObject(msg.getData());
        Long userId = jsonParse.getLong("userId");
        Player myPlayer = SessionManage.getChannel(userId);
        myPlayer.getUser().setState(UserState.ONLINE_STATE);/**修改为空闲状态*/

        SessionManage.delMatch(userId);
        NettyUtil.sendMsg(ctx.channel(), new RoomInfoVO(), GCmd.S2C.MATCH_PLAYER_CANCEL_SYNC.getDescription());
    }
}
